//
//  ShaoppingCarViewController.m
//  WeiWeiHaircut
//
//  Created by 超群 on 15/10/8.
//  Copyright © 2015年 超群. All rights reserved.
//

BOOL selectAll;

#import "ShaoppingCarViewController.h"
#import "ShoppingCarGoodsCell.h"
#import "OrderDetaliViewController.h"
#import "QZRequest.h"
#import "QZShopCarModel.h"
#import "MJRefresh.h"
@interface ShaoppingCarViewController () <UITableViewDataSource,UITableViewDelegate,QZRequestProtocol>
/** 全选 */
@property (weak, nonatomic) IBOutlet UIButton *allSelecteButton;
/** 下载类 */
@property (nonatomic, strong) QZRequest *request;
/** 商品数组 */
@property (strong, nonatomic) NSMutableArray *shops;
/** 选中的数组 */
@property (strong, nonatomic) NSMutableArray *allShops;
/** 页号 */
@property (nonatomic, assign) NSInteger pageno;

@end

@implementation ShaoppingCarViewController{
    NSArray* titleArray;
    NSArray* labeArray;
    CGFloat _allMoney;//总金额
    NSString *_changeType;//改变的类型
    NSInteger _changeNumber;//改变的数量
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleWithSting:@"购物车"];
    [self buildTableViewUI];
    [self buildUI];
    
    [self downloadDatas];
    selectAll = NO;
    
    [self refresh];
}
/**
 *  刷新 加载
 */
-(void)refresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageno = 1;
        _allSelecteButton.selected = NO;
        _allMoney = 0;
        _priceLabel.text = @"合计:￥ 0";
        self.request.isShowHUD = NO;
        [self downloadDatas];
        
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageno ++;
        self.request.isShowHUD = NO;
        [self downloadDatas];


    }];
    
    
}
-(NSMutableArray *)shops{
    if (_shops == nil) {
        _shops = [NSMutableArray array];
    }
    return _shops;
}
-(QZRequest *)request{
    if (_request == nil) {
        
        _request = [[QZRequest alloc] init];
        _request.delegate = self;
    }
    return _request;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)buildUI
{

    self.priceLabel.textColor = purColor2;
}

- (void)buildTableViewUI
{
    self.tableView.delegate         = self;
    self.tableView.dataSource       = self;
    self.tableView.separatorStyle   = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor  = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShoppingCarGoodsCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ShoppingCarGoodsCell class])];
}

#pragma mark- tableView delegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shops.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{

    QZShopCarModel *model = self.shops[indexPath.row];
    
    model.isSelect = !model.isSelect;
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO];
    
    if (model.isSelect) {
        _allMoney = _allMoney + model.prodMoney;
    }else{
        _allMoney = _allMoney - model.prodMoney;
    }
    _priceLabel.text = [NSString stringWithFormat:@"合计:￥%.2f",_allMoney];
    
    int selecteAll = 0;
    
    //判断是不是全选 ，全部都选中的话，让全选按钮选中
    for (QZShopCarModel *model  in self.shops) {
        
        if (!model.isSelect) {
            _allSelecteButton.selected = NO;
            break;
        }
        selecteAll ++;
    }
    
    if (selecteAll == self.shops.count) {
        _allSelecteButton.selected = YES;
    }
}

#pragma mark- tableView datasource
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    QZShopCarModel *model = self.shops[indexPath.row];
    
    ShoppingCarGoodsCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShoppingCarGoodsCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //增加和减少点击事件
    __weak ShoppingCarGoodsCell *mycell = cell;
      cell.changeBlock = ^(UIButton *btn){
        
        if (btn == mycell.addNumButton) {
            
           
            _changeType = @"add";
            model.amount = model.amount + 1;
            //在选中状态下改变 总金额
            if (mycell.selectButton.isSelected) {
                _allMoney = _allMoney +model.price2 ;
            }
            
            
        }else{
            
            if (model.amount<=1) {
                return ;
            }
            _changeType = @"minus";
            model.amount = model.amount - 1;
            //在选中状态下改变总金额
            if (mycell.selectButton.isSelected) {
            _allMoney = _allMoney -model.price2;
            }
        }
         model.prodMoney = model.amount * model.price2 ;
          //在选中状态下改变总金额
        if (mycell.selectButton.isSelected) {
        _priceLabel.text = [NSString stringWithFormat:@"合计:￥%.2f",_allMoney];
        }
        [self.tableView reloadData];
        [self changeShopNumber:model.detailId];
    };

    cell.shopModel = model;
    
    return cell;
}

#pragma mark 全选按钮
- (IBAction)selectAllTap:(UIButton *)sender {
    
    _allMoney = 0;

    sender.selected = !sender.selected;
    
    //给每个 都选中
    for (QZShopCarModel *model  in self.shops) {
        
        model.isSelect = sender.selected;
        if (sender.selected) {
            _allMoney = _allMoney + model.prodMoney ;
        }
    }

    _priceLabel.text = [NSString stringWithFormat:@"合计:￥%.2f",_allMoney];
    
    [self.tableView reloadData];
}
-(NSMutableArray *)allShops{
    if (!_allShops) {
        _allShops = [NSMutableArray array];
    }
    return _allShops;
}

#pragma mark- 结算按钮
- (IBAction)settlement:(UIButton *)sender {
    
    
    [self.allShops removeAllObjects];
    for (QZShopCarModel *model in self.shops) {
        if (model.isSelect) {
            [self.allShops addObject:model];
        }
    }
    
    if (self.allShops.count) {
        
        //先结算再跳转确
        [self createOrder];

    }else{
        [[iToast makeText:@"请选择商品"] show];
    }

}

#pragma mark 创建订单
-(void)createOrder{
   
    
     OrderDetaliViewController* payVC = [[OrderDetaliViewController alloc]initWithNibName:nil bundle:nil];
    payVC.settleAccounts = self.allShops;
    payVC.allMoney = _allMoney;
    payVC.hidesBottomBarWhenPushed  = YES;
    [self.navigationController pushViewController:payVC animated:YES];
}
#pragma mark- 下载数据
-(void)downloadDatas{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Details.GetDetailsList"];
    
    NSString *userID = [QZUserInfo userId];
    
    
    
    [self.request QZRequest_POST:url parameters:@{@"user_id":userID,@"page":@(_pageno),@"limit":@(7)} tagNSString:@"我的购物车" stopRequest:YES isSerializer:NO isCache:YES];
    

}
#pragma mark- 改变商品数量
- (void)changeShopNumber:(NSInteger)detail_id{
    
    NSString *url =[NSString stringWithFormat:@"%@%@",newPublicURL,@"Details.GetDetailsVary"];
    
    NSDictionary *dic = @{
                          @"vary":_changeType,
                          @"details_id":@(detail_id)
                          };
    
    self.request.isShowHUD = NO;
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"改变商品数量" stopRequest:YES isSerializer:NO isCache:NO];
    
    
}

#pragma mark- 下载回调代理
-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    
    
    [self.tableView.footer endRefreshing];
    [self.tableView.header endRefreshing];
    if ( [tag isEqualToString:@"我的购物车"]) {
        NSArray *array = value[@"data"][@"data"][@"list"];
        if (_pageno == 1) {
            
            [self.shops removeAllObjects];
        }
        
        if ([value[@"data"][@"status"] integerValue] == 101) {
            [self.tableView reloadData];
            [[iToast makeText:@"没有更多数据"] show];
            return;
        }
        
        for (NSDictionary *dic in array) {
            
            QZShopCarModel *model = [[QZShopCarModel alloc] initWithDictionary:dic error:nil];
            [self.shops addObject:model];
            
        }
        
        [self.tableView reloadData];
    }
    
    if ([tag isEqualToString:@"改变商品数量"]) {
        
        
    }

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _allSelecteButton.selected = NO;
    _allMoney = 0;
    
   _priceLabel.text = @"合计:￥ 0";
    [self.shops removeAllObjects];
    [self downloadDatas];
}
@end
